package com.lmn.oval;

import net.sf.oval.ValidationCycle;
import net.sf.oval.configuration.annotation.AbstractAnnotationCheck;
import net.sf.oval.exception.OValException;

/**
 * @version 4.0
 * @describe: 字符串校验实现
 * @author: houkai
 * @Date: 2019/1/15 10:12
 */
public class StringCheckImpl extends AbstractAnnotationCheck<StringCheck> {

    private static final long serialVersionUID = 6642122601539204946L;
    private int max;
    private int min;
    private boolean notNull;

    @Override
    public void configure(StringCheck stringCheck) {
        super.configure(stringCheck);
        setMax(stringCheck.max());
        setMin(stringCheck.min());
        setNotNull(stringCheck.notNull());
    }

    /**
     * @param validatedObject 进入校验器的对象
     * @param valueToValidate 注解当前标注的属性值
     * @return 是否通过验证
     * @throws OValException OValException
     */
    @Override
    public boolean isSatisfied(final Object validatedObject, final Object valueToValidate, final ValidationCycle cycle) throws OValException {
        String value = (String) valueToValidate;
        if (notNull) {
            // 如果需要校验非空，则校验是否为空
            if (!CheckUtil.isNotBlank(value)) {
                return false;
            }
        } else {
            if (!CheckUtil.isNotBlank(value)) {
                return true;
            }
        }
        // 最大长度校验
        if (value.length() > max) {
            return false;
        }
        // 最小长度校验
        if (min > 0) {
            if (value.length() < min) {
                return false;
            }
        }
        return true;
    }

    public int getMax() {
        return max;
    }

    public void setMax(int max) {
        this.max = max;
    }

    public int getMin() {
        return min;
    }

    public void setMin(int min) {
        this.min = min;
    }

    public boolean isNotNull() {
        return notNull;
    }

    public void setNotNull(boolean notNull) {
        this.notNull = notNull;
    }
}
